package com.example.administrator.helloworld;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import org.w3c.dom.Text;

import java.util.List;

public class FruitAdapter extends ArrayAdapter<Fruit> {
    private int resourceId;
    public FruitAdapter(Context context, int resource, List<Fruit> objects) {//activity.this,layout,list
        super(context, resource, objects);
        resourceId = resource;
    }
    @Override
    public View getView(int position,View convertView,ViewGroup parent){//该方法在每个子项被滚动到屏幕内的时候会被调用
        Fruit fruit = getItem(position);
        //View view = LayoutInflater.from(getContext()).inflate(resourceId,null);
        View view;
        ViewHolder viewHolder;
        if(convertView==null){//改进显示效率 重用convertView 便于快速滚动
            view=LayoutInflater.from(getContext()).inflate(resourceId,null);
            viewHolder = new ViewHolder((ImageView)view.findViewById(R.id.fruit_image),(TextView)view.findViewById(R.id.fruit_name));
            view.setTag(viewHolder);//将ViewHolder存储在View中
        }else{
            view=convertView;
            viewHolder = (ViewHolder)view.getTag();//重新获取ViewHolder
        }
        /*ImageView fruitImage = (ImageView) view.findViewById(R.id.fruit_image);
        TextView fruitName = (TextView) view.findViewById(R.id.fruit_name);
        fruitImage.setImageResource(fruit.getImageId());
        fruitName.setText(fruit.getName());*/
        viewHolder.fruitImage.setImageResource(fruit.getImageId());
        viewHolder.fruitName.setText(fruit.getName());
        return view;
    }
    class ViewHolder{//缓存 不用每次调用findViewById()
        ImageView fruitImage;
        TextView fruitName;
        ViewHolder(ImageView a,TextView b){
            this.fruitImage=a;
            this.fruitName=b;
        }
    }
}
